package com.roger.myHome.controller;

import com.roger.myHome.aspect.WebLog;
import com.roger.myHome.entity.dto.FinancialAddReq;
import com.roger.myHome.entity.dto.RedemptionDto;
import com.roger.myHome.entity.qto.FinancialQry;
import com.roger.myHome.entity.vo.FinancialDetailVo;
import com.roger.myHome.page.EUDataGridResult;
import com.roger.myHome.service.FinancialService;
import com.roger.myHome.util.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 理财管理控制层
 */
@RestController
@RequestMapping(value = "/financial")
public class FinancialController {

    private static List<String> PAGE_LIST = new ArrayList<>();

    static {
        PAGE_LIST = SystemUtil.getMenuUrlList();
    }

    @Resource
    private FinancialService financialService;

    @Resource
    private UserHelper userHelper;

    @PostMapping("/page")
    @WebLog
    public EUDataGridResult page(@RequestParam(value="page") String page,
                                 @RequestParam(value="rows") String rows, HttpServletRequest req){

        FinancialQry financialQry = new FinancialQry();

        financialQry.setBuyDate1(req.getParameter("buyDate1"));
        financialQry.setBuyDate2(req.getParameter("buyDate2"));
        financialQry.setState(req.getParameter("state"));
        financialQry.setChannel(req.getParameter("channel"));

        financialQry.setPage((Integer.parseInt(page) - 1) * Integer.parseInt(rows));
        financialQry.setRows(Integer.parseInt(rows));
        financialQry.setCreateUser(userHelper.getLoginUser(req).getId());
        return financialService.page(financialQry);
    }

    @PostMapping("/add")
    @WebLog
    public String add(HttpServletRequest req, FinancialAddReq financialAddReq){
        String result = null;
        try {
            result = BaseUtil.validate(financialAddReq);
        } catch (Exception e){
            e.printStackTrace();
        }

        if (!StringUtils.isNull(result)) {
            Map<String, String> hashMap = new HashMap();
            hashMap.put("result", result);
            return StringUtils.getJSONString(hashMap);
        }
        financialAddReq.setCreateUser(userHelper.getLoginUser(req).getId());
        return financialService.add(financialAddReq);
    }

    @PostMapping("/redemption")
    public String redemption(RedemptionDto redemptionDto){
        return financialService.redemption(redemptionDto);
    }

    @GetMapping("/checkIncome/{id}")
    public String checkIncome(@PathVariable Long id) throws Exception{
        return financialService.checkIncome(id);
    }

    @GetMapping("/searchTotalIncome")
    public String searchTotalIncome(){
        return financialService.searchTotalIncome();
    }

    @RequestMapping("/navigator")
    public ModelAndView navigator(HttpServletRequest request, HttpServletResponse response){
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + path + "/";

        String page = request.getParameter("page");
        //LoginUser loginUser = SystemUtil.getUserFromSession(request);
        Long userId = SystemUtil.getUserFromSession(request);
        if(isLogout(userId, page)){
            try{
                response.reset();
                response.setContentType("text/html;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<html>");
                out.println("<script>");
                out.println("window.open('"+basePath+"','_parent')");
                out.println("</script>");
                out.println("</html>");
            }catch(Exception e){
                System.err.println(e.getMessage());
            }
            return null;
        }else{
            ModelAndView mv = new ModelAndView();
            FinancialDetailVo vo = financialService.getVo(Long.valueOf(request.getParameter("id")));
            mv.addObject("vo", vo);
            mv.addObject("basePath", basePath);
            mv.setViewName(page);
            //mv.setViewName("/home/main");
            return mv;
        }
    }

    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable Long id){
        return financialService.delete(id);
    }

    private boolean isLogout(Long userId, String page){
        if (PAGE_LIST.contains(page)) {
            return false;
        } else if (userId == null || "logout".equalsIgnoreCase(page)){
            return true;
        } else {
            return true;
        }
    }
}
